import { createRouter, createWebHistory, createWebHashHistory } from "vue-router";
import { initDynamicRouter } from "@/routers/dynamicRouter";
import { useAuthStore } from "@/stores/modules/auth";

const routerMode = {
  hash: () => createWebHashHistory(APP_CONFIG.baseRoute),
  history: () => createWebHistory(APP_CONFIG.baseRoute),
};

const staticRoute = [
  {
    path: "/",
    redirect: APP_CONFIG.HOME_URL,
  },
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/login/index.vue"),
    meta: {
      title: "登录",
    },
  },
  {
    path: "/layout",
    name: "layout",
    component: () => import("@/layout/index.vue"),
    redirect: APP_CONFIG.HOME_URL,
    children: [],
  },
  {
    path: "/404",
    name: "404",
    component: () => import("@/views/err/404.vue"),
    meta: {
      title: "404页面",
    },
  },
  {
    path: "/:pathMatch(.*)*",
    component: () => import("@/views/err/404.vue"),
  },
];

const router = createRouter({
  history: routerMode[APP_CONFIG.routeMode](),
  routes: staticRoute,
});

/**
 * @description 路由拦截 beforeEach
 * */
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore();

  // 2.动态设置标题
  const title = APP_CONFIG.shortName;
  document.title = to.meta.title ? `${to.meta.title} - ${title}` : title;

  // 3.判断是访问登陆页，有 Token 就在当前页面，没有 Token 重置路由到登陆页
  if (to.path.toLocaleLowerCase() === APP_CONFIG.LOGIN_URL) {
    if (authStore.token) return next(from.fullPath);
    resetRouter();
    return next();
  }

  // 4.判断访问页面是否在路由白名单地址(静态路由)中，如果存在直接放行
  if (APP_CONFIG.ROUTER_WHITE_LIST.includes(to.path)) return next();

  // 5.判断是否有 Token，没有重定向到 login 页面
  if (!authStore.token) return next({ path: APP_CONFIG.LOGIN_URL, replace: true });

  // 6.如果没有菜单列表，就重新请求菜单列表并添加动态路由
  if (!authStore.authMenuListGet.length) {
    await initDynamicRouter();
    return next({ ...to, replace: true });
  }

  // 8.正常访问页面
  next();
});

/**
 * @description 重置路由
 * */
export const resetRouter = () => {
  const authStore = useAuthStore();
  authStore.flatMenuListGet.forEach((route) => {
    const { name } = route;
    if (name && router.hasRoute(name)) router.removeRoute(name);
  });
};

export default router;
